package com.wuhaha.a1911_demo;

import android.os.Bundle;
import android.text.TextUtils;
import android.view.MenuItem;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.Observer;
import androidx.navigation.NavController;
import androidx.navigation.fragment.NavHostFragment;

import com.google.android.material.bottomnavigation.BottomNavigationView;
import com.wuhaha.a1911_demo.model.Destination;
import com.wuhaha.a1911_demo.model.UserMessage;
import com.wuhaha.a1911_demo.ui.Login.UserManager;
import com.wuhaha.a1911_demo.utlis.AppConfig;
import com.wuhaha.a1911_demo.utlis.NavGraphBuilder;
import com.wuhaha.a1911_demo.view.AppBottomBar;

import org.jetbrains.annotations.NotNull;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

public class MainActivity extends AppCompatActivity implements BottomNavigationView.OnNavigationItemSelectedListener {
    private NavController navController;
    private AppBottomBar navView;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_main);
        BottomNavigationView navView = findViewById(R.id.nav_view);
        //设置导航控制器
        Fragment fragmentById = getSupportFragmentManager().findFragmentById(R.id.nav_host_fragment_activity_main);
        navController = NavHostFragment.findNavController(fragmentById);

        NavGraphBuilder.build(navController,this,fragmentById.getId());
        //选中监听
        navView.setOnNavigationItemSelectedListener(this);

    }

    //跳转到相关页面
    @Override
    public boolean onNavigationItemSelected(@NonNull @NotNull MenuItem item) {
        navController.navigate(item.getItemId());
        HashMap<String, Destination> destConfig = AppConfig.getsDestConfig();
        Iterator<Map.Entry<String, Destination>> iterator = destConfig.entrySet().iterator();
        //遍历 target destination 是否需要登录拦截
        while (iterator.hasNext()){
            Map.Entry<String,Destination> destinationEntry = iterator.next();
            Destination value = destinationEntry.getValue();
            if (value != null && !UserManager.get().isLogin() && value.needLogin && value.id == item.getItemId()) {
                //观察有没有登录成功
                UserManager.get().login(this).observe(this, new Observer<UserMessage>() {
                    @Override
                    public void onChanged(UserMessage userMessage) {
                        if (userMessage != null) {
                            navView.setSelectedItemId(item.getItemId());
                        }
                    }
                });
                return false;
            }
        }
        navController.navigate(item.getItemId());
        return !TextUtils.isEmpty(item.getTitle());
    }
}